/* eslint-disable @typescript-eslint/no-var-requires */
import { ref } from 'vue';
import { useGoldenLayout } from 'src/utils/goldenlayout';
import { LayoutConfig } from 'golden-layout';
import 'golden-layout/dist/css/goldenlayout-base.css';
import 'golden-layout/dist/css/themes/goldenlayout-dark-theme.css';
export default function (
  components: any,
  config: LayoutConfig,
  onInited?: () => void
) {
  interface ComponentInstance {
    id: number;
    type: string;
    element: HTMLElement;
  }
  let instanceId = 0;
  const componentTypes = new Set(Object.keys(components));
  const componentInstances = ref<ComponentInstance[]>([]);

  const createComponent = (type: string, element: HTMLElement) => {
    if (!componentTypes.has(type)) {
      throw new Error(`Component not found: '${type}'`);
    }
    ++instanceId;
    componentInstances.value = componentInstances.value.concat({
      id: instanceId,
      type,
      element,
    });
  };
  const destroyComponent = (toBeRemoved: HTMLElement) => {
    componentInstances.value = componentInstances.value.filter(
      ({ element }) => element !== toBeRemoved
    );
  };

  const { element, layout } = useGoldenLayout(
    createComponent,
    destroyComponent,
    config,
    onInited
  );
  window.onresize = () => {
    if (layout.value && element.value) {
      layout.value.setSize(
        element.value?.clientWidth,
        element.value?.clientHeight
      );
    }
  };
  return { element, componentInstances, layout };
}
